package eu.itract.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.cxf.common.message.CxfConstants;

import com.google.gson.Gson;

import eu.itract.service.domain.RitResource;

public class Router extends RouteBuilder {

	@Override
	public void configure() throws Exception {
		from("cxfrs://http://localhost:9090/?resourceClasses=" + RitResource.class.getName())
        .process(new Processor() {
            public void process(Exchange exchange) throws Exception {
            	Message inMessage = exchange.getIn();
            	
            	String operationName = inMessage.getHeader(CxfConstants.OPERATION_NAME, String.class);
            	
            	if("getRit".equals(operationName)){

            		String httpMethod = inMessage.getHeader(Exchange.HTTP_METHOD, String.class);
            		
            		if("GET".equals(httpMethod)){
            		
            			String van = inMessage.getBody(String.class);
                		String naar = inMessage.getBody(String.class);
                		String dag = inMessage.getBody(String.class);
                		String maand = inMessage.getBody(String.class);
                		String jaar = inMessage.getBody(String.class);
                		String tijd = inMessage.getBody(String.class);
                		
                		String jsonText = readJsonFromUrl("https://maps.googleapis.com/maps/api/directions/json?origin="+van+"&destination="+naar+"&sensor=false&mode=driving");
                
                		Gson gson = new Gson();
//                		JSONObject jsonObject = (JSONObject) jsonparser.parse(jsonText);
                		
//                		String status = (String) jsonObject.get("status");
                		
//                		if("ok".equals(status)){
                			
//                			JSONArray routes = (JSONArray) jsonObject.get("routes");
//                			Iterator<JSONObject> iterator = routes.iterator();
//                			
//                			while(iterator.hasNext()){
//                				JSONObject route = iterator.next();
//                				JSONArray legs = (JSONArray) route.get("legs");
//                				Iterator<JSONObject> it2 = legs.iterator();
//                    			
//                    			while(it2.hasNext()){
//                    				JSONObject leg = it2.next();
//                    				
//                    				JSONArray startLocation = (JSONArray) leg.get("start_location");
//                    				JSONArray endLocation = (JSONArray) leg.get("end_location");
//                    				
//                    				String start_lat = (String) startLocation.get(0);
//                    				String start_lng = (String) startLocation.get(1);
//                    				
//                    				String end_lat = (String) endLocation.get(0);
//                    				String end_lng = (String) endLocation.get(1);
//                    			}
//                			}
//                			
//                			//Route van / naar kan, d.w.z. er lopen wegen naar toe.
//                			String dbUrl = "jdbc:mysql://localhost/transports";
//                		    String dbClass = "com.mysql.jdbc.Driver";
//                		    String query = "Select distinct(table_name) from INFORMATION_SCHEMA.TABLES";
//                		    String username = "smx";
//                		    String password = "smx";
//                		    try {
//
//                		        Class.forName(dbClass);
//                		        Connection connection = DriverManager.getConnection(dbUrl,
//                		            username, password);
//                		        Statement statement = connection.createStatement();
//                		        ResultSet resultSet = statement.executeQuery(query);
//                		        
//                		        while (resultSet.next()) {
//	                		        String tableName = resultSet.getString(1);
//                		        }
//                		        connection.close();
//                		        
//                		        Response r = Response.status(200).entity(jsonText).build();
//                        		exchange.getOut().setBody(r);
//                            	return;
//                		    } catch (ClassNotFoundException e) {
//                		        e.printStackTrace();
//                		    } catch (SQLException e) {
//                		        e.printStackTrace();
//                		    }
                			
                			System.out.println("FOOBAR");
                			
                			Response r = Response.status(200).entity("FOOBAR").build();
                    		exchange.getOut().setBody(r);
                    		return;
                		    
//                		} else {
//                			System.out.println("FOOBAR 2");
//                			Response r = Response.status(404).entity("Route could not be calculated").build();
//                            throw new WebApplicationException(r);
//                		}
            			
            		}
                	
            	}
            	System.out.println("FOOBAR 3");
            	
                Response r = Response.status(404).entity("Incorrect service call" + operationName).build();
                throw new WebApplicationException(r);
            }
            
            private String readAll(Reader rd) throws IOException {
				StringBuilder sb = new StringBuilder();
				int cp;
				while ((cp = rd.read()) != -1) {
				  sb.append((char) cp);
				}
				return sb.toString();
            }

            private String readJsonFromUrl(String url) throws IOException {
            	InputStream is = new URL(url).openStream();
            	try {
					BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
					String jsonText = readAll(rd);
					return jsonText;
    			} finally {
    				is.close();
				}
            }
        });
	}

}
